import { getOffLineCodeUrl } from '@/api/OfflineStudy';
import { useAppSelector } from '@/redux/store';
import { DatePicker, Form, Radio, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import domtoimage from 'dom-to-image';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import OStyle from './codeModal.less';
const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};
const { RangePicker } = DatePicker;
interface DataType {
  key: React.Key;
  size: string;
  width: number;
  height: number;
  leng: string;
  qrTitleSize: number;
  qrTxtSize: number;
}
type codeObjType = {
  title: string;
  planTypeName: string;
  timeTxt: string;
  codeurl: string;
  codesize: number; //cm
  titSize: number; //px
  txtSize: number; //px
};

const ExportCodeModal = forwardRef<any, any>((props, ref) => {
  console.log(props, '打印看看属性');
  const { entName } = useAppSelector((state) => state.loginEnt);
  const { planCourseId, planTypeName } = props;
  const [form] = Form.useForm<any>();
  const codeTimeType = Form.useWatch('codeTimeType', form);
  const [seleKeys, setSeleKeys] = useState<any[]>([]);
  const [startTime, setStartTime] = useState<string>();
  const [endTime, setEndTime] = useState<string>();
  const [codeObj, setCodeObj] = useState<codeObjType>({
    title: '',
    planTypeName: '',
    timeTxt: '',
    titSize: 26,
    txtSize: 16,
    codeurl: '',
    codesize: 8,
  });
  const [downIng, setDownIng] = useState<boolean>(false);
  // const onRangeChange = (date: Dayjs, date2: any) => {
  //   if (date) {
  //     console.log('Date: ', date, date2);
  //   } else {
  //     console.log('Clear');
  //   }
  // };
  const sourceData: DataType[] = [
    {
      key: '1',
      size: 'a',
      width: 8,
      height: 8,
      qrTitleSize: 26,
      qrTxtSize: 16,
      leng: '0.5',
    },
    {
      key: '2',
      size: 'b',
      width: 12,
      height: 12,
      qrTitleSize: 42,
      qrTxtSize: 24,
      leng: '0.8',
    },
    {
      key: '3',
      size: 'c',
      width: 15,
      height: 15,
      qrTitleSize: 46,
      qrTxtSize: 30,
      leng: '1',
    },
    {
      key: '4',
      size: 'd',
      width: 30,
      height: 30,
      qrTitleSize: 92,
      qrTxtSize: 60,
      leng: '1.5',
    },
    {
      key: '5',
      size: 'e',
      width: 50,
      height: 50,
      qrTitleSize: 150,
      qrTxtSize: 100,
      leng: '2.5',
    },
  ];

  const columns: ColumnsType<DataType> = [
    {
      title: '二维码边长（cm）',
      dataIndex: 'size',
      render: (text: string, record) => (
        <>
          {record.width}×{record.height}
        </>
      ),
    },
    {
      title: '建议扫描距离（m）',
      dataIndex: 'leng',
      // render: (text: string) => <a>{text}</a>,
    },
    {
      title: '下载',
      dataIndex: 'down',
      render: (text: string, record) => (
        <>
          <div
            style={{ cursor: 'pointer' }}
            onClick={() => {
              form.validateFields().then((values) => {
                if (downIng) {
                  return;
                }
                setCodeObj({
                  title: '',
                  planTypeName: '',
                  timeTxt: '',
                  titSize: 26,
                  txtSize: 16,
                  codeurl: '',
                  codesize: 8,
                });
                setDownIng(true);
                const params = {
                  wSize: record.width * 40,
                  hSize: record.height * 40,
                  msg: '',
                };
                const msgBefore = 'yunMai56/qrCode/Learning/card?planId=' + planCourseId + '&startDate=';
                let startTimeStr = '';
                let endTimeStr = '';
                if (values.codeTimeType == 1) {
                  params.msg = msgBefore + '2000-01-05 00:00:00&endDate=2999-12-31 23:59:59';
                } else if (values.codeTimeType == 2) {
                  params.msg = msgBefore + startTime + '&endDate=' + endTime;
                  startTimeStr = dayjs(startTime).format('YYYY年MM月DD日 HH:mm');
                  endTimeStr = dayjs(endTime).format('YYYY年MM月DD日 HH:mm');
                }

                getOffLineCodeUrl(params).then((res: any) => {
                  const { code, data } = res;
                  console.log(data, '打印看看日期');
                  if (code === '200') {
                    setCodeObj({
                      title: entName || localStorage.getItem('entName') || '',
                      planTypeName: planTypeName,
                      timeTxt: values.codeTimeType == 1 ? '' : startTimeStr + ' ~ ' + endTimeStr,
                      titSize: record.qrTitleSize,
                      txtSize: record.qrTxtSize,
                      codeurl: data,
                      codesize: record.width,
                    });
                    // window.open(data, '_target');
                    // const nodeDom: HTMLElement = qecodeHtml(data) as HTMLElement;
                  }
                });
              });
            }}
          >
            下载
          </div>
        </>
      ),
    },
  ];
  useEffect(() => {
    if (codeObj.codeurl) {
      const nodeDom = document.getElementById('node');
      if (!nodeDom) {
        console.log('err:未获取到dom');
        return;
      }
      setDownIng(false);
      // const nodeDom = codeDom(codeObj);
      domtoimage
        .toPng(nodeDom as unknown as Node, { bgcolor: '#fff', cacheBust: true })
        .then((defaultUrl) => {
          const link = document.createElement('a');
          link.download = '二维码.png';
          link.href = defaultUrl;
          link.click();
        })
        .catch((error) => {
          console.log('error', error);
        });
    }
  }, [codeObj]);

  const onSubmit = () => {
    return form
      .validateFields()
      .then((values) => {
        // const params = {
        //   wSize: sourceData[seleKeys[0]].width,
        //   hSize: sourceData[seleKeys[0]].height,
        //   msg: '',
        // };
        // const msgBefore = 'yunMai56/qrCode/Learning/card?planId=' + planCourseId + '&startDate=';
        // if (values.codeTimeType == 1) params.msg = msgBefore + '2000-01-05 00:00:00&endDate=2999-12-31 23:59:59';
        // else if (values.codeTimeType == 2) params.msg = msgBefore + startTime + '&endDate=' + endTime;
        return Promise.resolve({
          codePros: values,
          planCourseId: planCourseId,
          selectArr: seleKeys,
          startTime,
          endTime,
        });
      })
      .catch((err) => {
        return Promise.reject(err);
      });
  };
  useImperativeHandle(ref, () => ({
    onSubmit,
  }));
  return (
    <div style={{ padding: '16px 16px 0' }}>
      <div className={OStyle.codeModel}>
        <div id="node" className={OStyle.node_dom} style={{ background: '#fff', textAlign: 'center' }}>
          <div
            style={{
              width: codeObj.codesize + 2 + 'cm',
              marginTop: codeObj.titSize - 6 + 'px',
              marginBottom: codeObj.titSize - 6 + 'px',
              textAlign: 'center',
              fontSize: codeObj.titSize + 'px',
              fontWeight: 600,
              color: '#333',
              lineHeight: 1.5,
            }}
          >
            {codeObj.title}
          </div>
          <div
            style={{
              background: '#FF6D3B',
              borderTopLeftRadius: codeObj.txtSize + 'px',
              borderTopRightRadius: codeObj.txtSize + 'px',
              paddingTop: codeObj.titSize + 4 + 'px',
              paddingLeft: codeObj.titSize + 4 + 'px',
              paddingRight: codeObj.titSize + 4 + 'px',
              paddingBottom: codeObj.titSize + 'px',
            }}
          >
            <div style={{ background: '#fff', borderRadius: codeObj.txtSize + 'px' }}>
              <div
                style={{
                  background: '#fff',
                  borderRadius: codeObj.txtSize + 'px',
                  overflow: 'hidden',
                  padding: codeObj.titSize - 4 + 'px',
                }}
              >
                <img
                  src={codeObj.codeurl}
                  style={{ width: codeObj.codesize + 'cm', height: codeObj.codesize + 'cm' }}
                ></img>
              </div>
              <div
                style={{
                  borderTop: '1px solid #E9E9E9',
                  textAlign: 'center',
                  position: 'relative',
                  fontWeight: 600,
                  fontSize: codeObj.txtSize + 2 + 'px',
                  color: '#333',
                  paddingTop: codeObj.txtSize + 'px',
                  paddingBottom: codeObj.txtSize + 'px',
                  lineHeight: codeObj.txtSize + 2 + 'px',
                }}
              >
                <div
                  style={{
                    width: codeObj.txtSize,
                    height: codeObj.txtSize,
                    borderRadius: '50%',
                    background: '#FF6D3B',
                    position: 'absolute',
                    top: -codeObj.txtSize / 2,
                    left: -codeObj.txtSize / 2,
                  }}
                ></div>
                <div
                  style={{
                    width: codeObj.txtSize,
                    height: codeObj.txtSize,
                    borderRadius: '50%',
                    background: '#FF6D3B',
                    position: 'absolute',
                    top: -codeObj.txtSize / 2,
                    right: -codeObj.txtSize / 2,
                  }}
                ></div>
                {codeObj.planTypeName}签到二维码
              </div>
            </div>
            {codeObj.timeTxt ? (
              <div>
                <p
                  style={{
                    marginTop: codeObj.txtSize + 2,
                    color: '#fff',
                    fontSize: codeObj.txtSize + 'px',
                    lineHeight: codeObj.txtSize + 'px',
                  }}
                >
                  二维码有效期
                </p>
                <p
                  className="node-title"
                  style={{
                    marginTop: codeObj.txtSize / 2,
                    color: '#fff',
                    fontSize: codeObj.txtSize + 'px',
                    lineHeight: codeObj.txtSize + 'px',
                  }}
                >
                  {codeObj.timeTxt}
                </p>
              </div>
            ) : null}
          </div>
        </div>
      </div>
      <Form layout="horizontal" form={form}>
        <Form.Item label="二维码有效期" name="codeTimeType" rules={requireRules('请选择二维码有效期')}>
          <Radio.Group>
            <Radio value={1}>永久有效</Radio>
            <Radio value={2}>固定时间有效</Radio>
          </Radio.Group>
        </Form.Item>
        {/* <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.codeTimeType !== currentValues.codeTimeType}
        >
          {({ getFieldValue }) =>
            getFieldValue('codeTimeType') === 2 ? (
              <Form.Item label="有效期时间" name="effectTime" rules={requireRules('请选择有效期时间')}>
                <RangePicker
                  showTime
                  format="YYYY-MM-DD HH:mm"
                  onChange={(date: any, date2: any) => {
                    if (date) {
                      setStartTime(date2[0]);
                      setEndTime(date2[1]);
                    } else {
                      console.log('Clear');
                    }
                  }}
                />
              </Form.Item>
            ) : null
          }
        </Form.Item> */}
        {codeTimeType === 2 ? (
          <Form.Item label="有效期时间" name="effectTime" rules={requireRules('请选择有效期时间')}>
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm"
              onChange={(date: any, date2: any) => {
                if (date) {
                  setStartTime(date2[0]);
                  setEndTime(date2[1]);
                } else {
                  console.log('Clear');
                }
              }}
            />
          </Form.Item>
        ) : null}
        <Form.Item label="二维码尺寸" name="widHei">
          <Table columns={columns} dataSource={sourceData} pagination={false} />
        </Form.Item>
      </Form>
    </div>
  );
});
export default ExportCodeModal;
